package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.*;
import com.sc.nft.dto.ADDEcologyIncomeDetailsConfDTO;
import com.sc.nft.dto.EcologyHatchConfDao;
import com.sc.nft.dto.ResonanceServiceCenterCoefficientConfDTO;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.EcologyHatchExtraRewardsMethodConfDTO;
import com.sc.nft.entity.req.ADDEcologyIncomeServiceCenterConfRequest;
import com.sc.nft.entity.req.AddEcologyIncomeCollectionRequest;
import com.sc.nft.entity.req.AddEcologyIncomeConfSingleRequest;
import com.sc.nft.entity.vo.CoefficientVO;
import com.sc.nft.entity.vo.ecology.*;
import com.sc.nft.entity.vo.merchantPledgeTask.AdminEcologyIncomeConfListVO;
import com.sc.nft.entity.vo.merchantPledgeTask.NewAdminEcologyIncomeConfDetailsVO;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.AdminEcologyIncomeConfService;
import com.sc.nft.service.EcologyCollectionShareProfitConfService;
import com.sc.nft.service.EcologyShareProfitServiceCenterConfService;
import com.sc.nft.util.BigDecimalUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminEcologyIncomeConfServiceImpl implements AdminEcologyIncomeConfService {

    private final EcologyHatchConfDao ecologyHatchConfDao;
    private final EcologyHatchCollecionShareProfitConfDao cologyHatchCollecionShareProfitConfDao;
    private final DigitalCollectionDao digitalCollectionDao;
    private final UserCreatorInfoDao userCreatorInfoDao;
    private final EcologyHatchShareIncomeConfDao ecologyHatchShareIncomeConfDao;
    private final EcologyHatchCollecionShareProfitConfDao ecologyHatchCollecionShareProfitConfDao;
    private final EcologyHatchDivideIntoLogDao ecologyHatchDivideIntoLogDao;
    private final EcologyHatchShareProfitMethodConfDao ecologyHatchShareProfitMethodConfDao;
    private final ResonanceServiceCenterCoefficientConfDao resonanceServiceCenterCoefficientConfDao;
    private final UserInfoDao userInfoDao;
    private final EcologyCollectionShareProfitConfService ecologyCollectionShareProfitConfService;
    private final EcologyShareProfitServiceCenterConfService ecologyShareProfitServiceCenterConfService;

    /**
     * 新增生态收益配置
     *
     * @param confId                      生态铸造配置id
     * @param platformNotDivideIntoNum    市值管理平台不分成份数
     * @param daoNotDivideIntoNum         市值管理品牌不分成份数
     * @param type                        分润类型
     * @param resonanceStatus             是否开启共振
     * @param resonanceServiceCenterDaoId 共振服务中心DaoId
     * @param confDetailsList             生态配置详情
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addConf(Long confId, Integer platformNotDivideIntoNum, Integer daoNotDivideIntoNum, EcologyHatchShareProfitMethodConfTypeEnum type, Boolean resonanceStatus,
                        Long resonanceServiceCenterDaoId, List<ADDEcologyIncomeDetailsConfDTO> confDetailsList, List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOList) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(confId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态熔炼配置不存在"));

        EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(confId);
        Assert.isFalse(Objects.nonNull(ecologyHatchShareProfitMethodConf) && ecologyHatchShareProfitMethodConf.getType() == type, () -> new GlobalRunTimeException("生态熔炼分润配置已存在"));
        Assert.isTrue(EcologyHatchShareProfitMethodConfTypeEnum.all().contains(type), () -> new GlobalRunTimeException("未知分润方式"));
        if (Objects.isNull(resonanceStatus)) {
            resonanceStatus = Boolean.FALSE;
        }
        Long resonanceDaoId = null;
        if (resonanceStatus) {
            // 是否开启共振
            if (Objects.nonNull(ecologyHatchShareProfitMethodConf)) {
                if (Objects.nonNull(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId())) {
                    resonanceServiceCenterDaoId = ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId();
                }
                if (Objects.nonNull(ecologyHatchShareProfitMethodConf.getResonanceDaoId())) {
                    resonanceDaoId = ecologyHatchShareProfitMethodConf.getResonanceDaoId();
                }
            } else {
                Assert.notNull(resonanceServiceCenterDaoId, () -> new GlobalRunTimeException("共振服务中心Dao不可为空"));
                List<EcologyHatchConf> ecologyHatchConfs = ecologyHatchConfDao.list();
                List<Long> daoIds = ecologyHatchConfs.stream().map(EcologyHatchConf::getDaoId).collect(Collectors.toList());
                Assert.isFalse(daoIds.contains(resonanceServiceCenterDaoId), () -> new GlobalRunTimeException("品牌方不能作为共振方"));
                EcologyHatchShareProfitMethodConf oneByResonanceServiceCenterDaoId = ecologyHatchShareProfitMethodConfDao.getOneByResonanceServiceCenterDaoId(resonanceServiceCenterDaoId, null);
                Assert.isNull(oneByResonanceServiceCenterDaoId, () -> new GlobalRunTimeException("该dao已经是共振方"));
            }
            Assert.notNull(userCreatorInfoDao.getById(resonanceServiceCenterDaoId), () -> new GlobalRunTimeException("共振城市服务中心不存在"));
        }

        // 移除之前的分润配置
        ecologyHatchCollecionShareProfitConfDao.delByConfId(confId);
        ecologyHatchShareIncomeConfDao.delByConfId(confId);
        resonanceServiceCenterCoefficientConfDao.removeByConfId(confId);

        // 总分润
        BigDecimal totalDistributionScale = BigDecimal.ZERO;

        for (ADDEcologyIncomeDetailsConfDTO addEcologyIncomeDetailsConfDTO : confDetailsList) {

            totalDistributionScale = totalDistributionScale.add(addEcologyIncomeDetailsConfDTO.getDistributionScale());
            Assert.isTrue(NumberUtil.isGreaterOrEqual(addEcologyIncomeDetailsConfDTO.getDistributionScale(), BigDecimal.ZERO), () -> new GlobalRunTimeException("分配比例必须大于0"));

            EcologyHatchCollecionShareProfitConf ecologyHatchCollecionShareProfitConf = new EcologyHatchCollecionShareProfitConf();
            ecologyHatchCollecionShareProfitConf.setConfId(confId);
            ecologyHatchCollecionShareProfitConf.setCollectionId(ecologyHatchConf.getCollectionId());
            ecologyHatchCollecionShareProfitConf.setPlatformDaoId(DaoInfoEnum.META_DAO.getId());
            UserCreatorInfo dao = null;
            if (Objects.nonNull(addEcologyIncomeDetailsConfDTO.getDaoId())) {
                dao = userCreatorInfoDao.getById(addEcologyIncomeDetailsConfDTO.getDaoId());
                Assert.notNull(dao, () -> new GlobalRunTimeException("品牌Dao不可为空"));
            }
            switch (addEcologyIncomeDetailsConfDTO.getType()) {
                case SHARE_PROFIT:
                    //直推收益
                    List<Long> collectionIds = addEcologyIncomeDetailsConfDTO.getCollectionIds();
                    List<DigitalCollection> collections = digitalCollectionDao.getByIds(collectionIds);
                    Assert.isTrue(collections.size() == collectionIds.size(), () -> new GlobalRunTimeException("藏品id错误"));

                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.SHARE_PROFIT);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.SHARE_PROFIT.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(DaoInfoEnum.META_DAO.getId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);

                    for (DigitalCollection collection : collections) {
                        EcologyHatchShareIncomeConf ecologyHatchShareIncomeConf = new EcologyHatchShareIncomeConf();
                        ecologyHatchShareIncomeConf.setConfId(confId);
                        ecologyHatchShareIncomeConf.setCollectionId(collection.getId());
                        ecologyHatchShareIncomeConf.setCollectionName(collection.getFirstTitle());
                        ecologyHatchShareIncomeConf.setIncomeScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                        ecologyHatchShareIncomeConf.insert();
                    }
                    break;
                case PLATFORM_DIVIDE:
                    Assert.isTrue(EcologyHatchShareProfitMethodConfTypeEnum.FIXED_PROPORTION == type, () -> new GlobalRunTimeException("该分润方式没有平台分润池类型"));
                    //平台分红池
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(DaoInfoEnum.META_DAO.getId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);

                    break;
                case DAO_DIVIDE:
                    //DAO分红池
                    Assert.isTrue(EcologyHatchShareProfitMethodConfTypeEnum.FIXED_PROPORTION == type, () -> new GlobalRunTimeException("该分润方式没有DAO分润池类型"));

                    Assert.notNull(dao, () -> new GlobalRunTimeException("DAO不存在"));

                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.DAO_DIVIDE);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.DAO_DIVIDE.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(dao.getId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);
                    break;
                case RISK_POOL:
                    //风控池
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.RISK_POOL);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.RISK_POOL.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(DaoInfoEnum.META_DAO.getId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);
                    break;
                case TECHNICAL_SERVICE_FEE:
                    //技术服务费
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.TECHNICAL_SERVICE_FEE);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.TECHNICAL_SERVICE_FEE.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(DaoInfoEnum.META_DAO.getId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);
                    break;
                case BOTH_PARTIES_ACCOUNT:
                    //双方分账
                    Assert.notNull(addEcologyIncomeDetailsConfDTO.getSeparateAccountType(), () -> new GlobalRunTimeException("双方分账类型不能为空"));
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT.getDescription());
                    ecologyHatchCollecionShareProfitConf.setDaoId(addEcologyIncomeDetailsConfDTO.getDaoId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(addEcologyIncomeDetailsConfDTO.getPlatformDivideScale());
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(addEcologyIncomeDetailsConfDTO.getDaoDivideIntoScale());

                    BigDecimal bothPartiesAccount = addEcologyIncomeDetailsConfDTO.getDaoDivideIntoScale().add(addEcologyIncomeDetailsConfDTO.getPlatformDivideScale());
                    Assert.isTrue(NumberUtil.equals(bothPartiesAccount, Convert.toBigDecimal(100)), () -> new GlobalRunTimeException("平台分成比例和DAO分成比例之和必须为100%"));
                    break;
                case MARKET_VALUE_MANAGEMENT:
                    Assert.notNull(dao, () -> new GlobalRunTimeException("DAO不存在"));
                    //市值管理
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT.getDescription());
                    // 品牌DaoId
                    ecologyHatchCollecionShareProfitConf.setDaoId(dao.getId());
                    // 总分配比例
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(addEcologyIncomeDetailsConfDTO.getPlatformDivideScale());
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(addEcologyIncomeDetailsConfDTO.getDaoDivideIntoScale());
                    if (EcologyHatchShareProfitMethodConfTypeEnum.FIXED_PROPORTION == type) {
                        // 固定比例
                        BigDecimal marketValueManagement = addEcologyIncomeDetailsConfDTO.getDaoDivideIntoScale().add(addEcologyIncomeDetailsConfDTO.getPlatformDivideScale());
                        Assert.isTrue(NumberUtil.equals(marketValueManagement, Convert.toBigDecimal(100)), () -> new GlobalRunTimeException("平台分成比例和品牌分成比例之和必须为100%"));
                    } else {
                        // 谁熔炼归谁
                        if (Objects.isNull(resonanceDaoId)) {
                            resonanceDaoId = dao.getId();
                        }
                        ecologyHatchCollecionShareProfitConf.setDaoId(resonanceDaoId);
                        // 品牌拉新人数
                        ecologyHatchCollecionShareProfitConf.setDaoNewUserNum(addEcologyIncomeDetailsConfDTO.getDaoNewUserNum());
                        if (resonanceStatus) {
                            // 服务中心拉新人数
                            ecologyHatchCollecionShareProfitConf.setServiceCenterNewUserNum(addEcologyIncomeDetailsConfDTO.getServiceCenterNewUserNum());
                            // 是否开启共振
                            ecologyHatchCollecionShareProfitConf.setServiceCenterDaoId(resonanceServiceCenterDaoId);
                            // 共振 品牌 服务中心分成比例
                            ecologyHatchCollecionShareProfitConf.setResonanceDaoDivideIntoScale(addEcologyIncomeDetailsConfDTO.getResonanceDaoDivideIntoScale());
                            ecologyHatchCollecionShareProfitConf.setResonanceServiceCenterDaoDivideIntoScale(addEcologyIncomeDetailsConfDTO.getResonanceServiceCenterDaoDivideIntoScale());
                            BigDecimal resonanceDivideIntoScale = addEcologyIncomeDetailsConfDTO.getResonanceDaoDivideIntoScale().add(addEcologyIncomeDetailsConfDTO.getResonanceServiceCenterDaoDivideIntoScale());
                            Assert.isTrue(NumberUtil.equals(resonanceDivideIntoScale, Convert.toBigDecimal(100)), () -> new GlobalRunTimeException("共振分成比例之和必须为100%"));
                        }
                    }
                    break;
                case PER_DIVIDEND_POOL:
                    Assert.isTrue(EcologyHatchShareProfitMethodConfTypeEnum.SMELTER_SMELTER == type, () -> new GlobalRunTimeException("该分润方式没有每份分润池类型"));
                    // 每份分红池 (平台分红池 + DAO分红池) 不同方式 比例计算不同
                    ecologyHatchCollecionShareProfitConf.setType(EcologyHatchShareProfitTypeEnum.PER_DIVIDEND_POOL);
                    ecologyHatchCollecionShareProfitConf.setTypeName(EcologyHatchShareProfitTypeEnum.PER_DIVIDEND_POOL.getDescription());
                    // 品牌DaoId
                    ecologyHatchCollecionShareProfitConf.setDaoId(addEcologyIncomeDetailsConfDTO.getDaoId());
                    ecologyHatchCollecionShareProfitConf.setDistributionScale(addEcologyIncomeDetailsConfDTO.getDistributionScale());
                    ecologyHatchCollecionShareProfitConf.setServiceCenterDaoId(resonanceServiceCenterDaoId);
                    ecologyHatchCollecionShareProfitConf.setPlatformDivideScale(BigDecimal.ZERO);
                    ecologyHatchCollecionShareProfitConf.setDaoDivideIntoScale(BigDecimal.ZERO);

                    break;
                default:
                    throw new GlobalRunTimeException("生态铸造配置类型错误");
            }
            ecologyHatchCollecionShareProfitConf.insert();
        }
        Assert.isTrue(NumberUtil.equals(totalDistributionScale.movePointLeft(2), BigDecimal.ONE), () -> new GlobalRunTimeException("分配比例总和必须为100%"));

        // 谁熔炼归谁 计算城市服务中心分润系数
        BigDecimal resonanceServiceCenterCoefficient = BigDecimal.ZERO;
        if (EcologyHatchShareProfitMethodConfTypeEnum.SMELTER_SMELTER == type && resonanceStatus) {
            Assert.isTrue(!CollectionUtils.isEmpty(resonanceServiceCenterCoefficientConfDTOList) && resonanceServiceCenterCoefficientConfDTOList.size() > 0, () -> new GlobalRunTimeException("共振服务中心系数考核配置不得为空"));
            CoefficientVO coefficientVO = getCoefficient(resonanceServiceCenterDaoId, confId, ecologyHatchConf, resonanceServiceCenterCoefficientConfDTOList);
            // 城市服务中心分润系数
            resonanceServiceCenterCoefficient = coefficientVO.getCoefficient();
            // 共振服务中心系数
            List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOs = coefficientVO.getResonanceServiceCenterCoefficientConfDTOList();
            for (int i = 0; i < resonanceServiceCenterCoefficientConfDTOs.size(); i++) {
                ResonanceServiceCenterCoefficientConfDTO resonanceServiceCenterCoefficientConfDTO = resonanceServiceCenterCoefficientConfDTOs.get(i);
                ResonanceServiceCenterCoefficientConf resonanceServiceCenterCoefficientConf = new ResonanceServiceCenterCoefficientConf();
                BeanUtil.copyProperties(resonanceServiceCenterCoefficientConfDTO, resonanceServiceCenterCoefficientConf);
                resonanceServiceCenterCoefficientConf.setLevel(i + 1);
                resonanceServiceCenterCoefficientConf.setEcologyHatchId(confId);
                resonanceServiceCenterCoefficientConf.insert();
            }
        }
        if (Objects.nonNull(ecologyHatchShareProfitMethodConf)) {
            // 修改分润方式 只能修改方式
            if (Objects.nonNull(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId())) {
                // 配置共振
                resonanceServiceCenterDaoId = null;
                resonanceDaoId = null;
            }
            ecologyHatchShareProfitMethodConfDao.updateByEcologyHatchId(ecologyHatchConf.getId(), type, resonanceStatus, resonanceServiceCenterCoefficient, resonanceServiceCenterDaoId, resonanceDaoId, ecologyHatchShareProfitMethodConf);
        } else {
            // 分润方式
            ecologyHatchShareProfitMethodConf = new EcologyHatchShareProfitMethodConf();
            ecologyHatchShareProfitMethodConf.setEcologyHatchId(ecologyHatchConf.getId());
            ecologyHatchShareProfitMethodConf.setDaoNotDivideIntoNum(daoNotDivideIntoNum);
            ecologyHatchShareProfitMethodConf.setPlatformNotDivideIntoNum(platformNotDivideIntoNum);
            ecologyHatchShareProfitMethodConf.setType(type);
            ecologyHatchShareProfitMethodConf.setResonanceStatus(resonanceStatus);
            ecologyHatchShareProfitMethodConf.setResonanceDaoId(resonanceDaoId);
            ecologyHatchShareProfitMethodConf.setResonanceServiceCenterDaoId(resonanceServiceCenterDaoId);
            ecologyHatchShareProfitMethodConf.setResonanceServiceCenterCoefficient(resonanceServiceCenterCoefficient);
            ecologyHatchShareProfitMethodConf.insert();
        }
    }

    /**
     * 获取城市服务中心对应的系数
     *
     * @param resonanceServiceCenterDaoId
     * @param confId
     * @param ecologyHatchConf
     * @param resonanceServiceCenterCoefficientConfDTOList
     * @return
     */
    @Override
    public CoefficientVO getCoefficient(Long resonanceServiceCenterDaoId, Long confId, EcologyHatchConf ecologyHatchConf, List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOList) {
        BigDecimal returnCoefficient = BigDecimal.ZERO;
        // 按照最低值进行排序
        List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOS = resonanceServiceCenterCoefficientConfDTOList.stream()
                .sorted(Comparator.comparingInt(ResonanceServiceCenterCoefficientConfDTO::getMinNum))
                .collect(Collectors.toList());
        Integer previousMax = 0;
        if (Objects.isNull(ecologyHatchConf)) {
            ecologyHatchConf = ecologyHatchConfDao.getById(confId);
            Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态熔炼配置不存在"));
        }
        UserCreatorInfo daoUser = userCreatorInfoDao.getById(ecologyHatchConf.getDaoId());
        UserCreatorInfo resonanceServiceCenter = null;
        Integer userNum = 0;
        if (Objects.nonNull(resonanceServiceCenterDaoId)) {
            resonanceServiceCenter = userCreatorInfoDao.getById(resonanceServiceCenterDaoId);
            Assert.notNull(resonanceServiceCenter, () -> new GlobalRunTimeException("城市服务中心DAO不存在"));
            userNum = userInfoDao.getCountValidByUserId(resonanceServiceCenter.getUserId(), daoUser.getUserId());
        }

        for (int i = 0; i < resonanceServiceCenterCoefficientConfDTOS.size(); i++) {
            ResonanceServiceCenterCoefficientConfDTO resonanceServiceCenterCoefficientConfDTO = resonanceServiceCenterCoefficientConfDTOS.get(i);
            if (BigDecimalUtils.compare(resonanceServiceCenterCoefficientConfDTO.getCoefficient(), 100)) {
                throw new GlobalRunTimeException("生态系数不得大于百分之100");
            }
            if (i == 0) {
                // 最小范围的最小值必须为0
                resonanceServiceCenterCoefficientConfDTO.setMinNum(0);
                if (i == resonanceServiceCenterCoefficientConfDTOS.size() - 1) {
                    resonanceServiceCenterCoefficientConfDTO.setMaxNum(999999);
                }
            } else if (i == resonanceServiceCenterCoefficientConfDTOS.size() - 1) {
                resonanceServiceCenterCoefficientConfDTO.setMaxNum(999999);
            } else {
                Assert.isTrue(previousMax.equals(resonanceServiceCenterCoefficientConfDTO.getMinNum()), () -> new GlobalRunTimeException("范围配置有误"));
            }
            previousMax = resonanceServiceCenterCoefficientConfDTO.getMaxNum();
            if (Objects.nonNull(resonanceServiceCenter)) {
                if (resonanceServiceCenterCoefficientConfDTO.getMinNum() < userNum && resonanceServiceCenterCoefficientConfDTO.getMaxNum() >= userNum) {
                    returnCoefficient = resonanceServiceCenterCoefficientConfDTO.getCoefficient();
                }
            }
        }
        CoefficientVO coefficientVO = new CoefficientVO();
        coefficientVO.setCoefficient(returnCoefficient);
        coefficientVO.setResonanceServiceCenterCoefficientConfDTOList(resonanceServiceCenterCoefficientConfDTOS);
        return coefficientVO;
    }

    private List<ResonanceServiceCenterCoefficientConfDTO> buildResonanceServiceCenterCoefficientConfDTOList(List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOList) {
        List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOS = resonanceServiceCenterCoefficientConfDTOList.stream()
                .sorted(Comparator.comparingInt(ResonanceServiceCenterCoefficientConfDTO::getMinNum))
                .collect(Collectors.toList());
        Integer previousMax = 0;
        for (int i = 0; i < resonanceServiceCenterCoefficientConfDTOS.size(); i++) {
            ResonanceServiceCenterCoefficientConfDTO resonanceServiceCenterCoefficientConfDTO = resonanceServiceCenterCoefficientConfDTOS.get(i);
            if (i == 0) {
                // 最小范围的最小值必须为0
                resonanceServiceCenterCoefficientConfDTO.setMinNum(0);
                if (i == resonanceServiceCenterCoefficientConfDTOS.size() - 1) {
                    resonanceServiceCenterCoefficientConfDTO.setMaxNum(999999);
                }
            } else if (i == resonanceServiceCenterCoefficientConfDTOS.size() - 1) {
                resonanceServiceCenterCoefficientConfDTO.setMaxNum(999999);
            } else {
                Assert.isTrue(previousMax.equals(resonanceServiceCenterCoefficientConfDTO.getMinNum()), () -> new GlobalRunTimeException("范围配置有误"));
            }
            previousMax = resonanceServiceCenterCoefficientConfDTO.getMaxNum();

        }
        return resonanceServiceCenterCoefficientConfDTOS;
    }

    @Override
    public AdminEcologyHatchCollecionShareProfitConfDetailsVO getConfById(Long id) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(id);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));

        AdminEcologyHatchCollecionShareProfitConfDetailsVO vo = new AdminEcologyHatchCollecionShareProfitConfDetailsVO();
        // 获取分润方式
        EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(id);
        if (Objects.isNull(ecologyHatchShareProfitMethodConf)) {
            return vo;
        }
        BeanUtil.copyProperties(ecologyHatchShareProfitMethodConf, vo);
        // 获取分润配置
        List<EcologyHatchCollecionShareProfitConf> confList = cologyHatchCollecionShareProfitConfDao.getListByConfId(id);
        List<AdminEcologyIncomeConfDetailsVO> list = Lists.newArrayList();
        for (EcologyHatchCollecionShareProfitConf ecologyHatchCollecionShareProfitConf : confList) {
            AdminEcologyIncomeConfDetailsVO adminEcologyIncomeConfDetailsVO = new AdminEcologyIncomeConfDetailsVO();
            BeanUtil.copyProperties(ecologyHatchCollecionShareProfitConf, adminEcologyIncomeConfDetailsVO);

            if (ecologyHatchCollecionShareProfitConf.getType() == EcologyHatchShareProfitTypeEnum.SHARE_PROFIT) {
                List<EcologyHatchShareIncomeConf> collectioList = ecologyHatchShareIncomeConfDao.getListByConfId(id);
                List<Long> collectionId = collectioList.stream().map(EcologyHatchShareIncomeConf::getCollectionId).collect(Collectors.toList());
                List<String> collectionNames = collectioList.stream().map(EcologyHatchShareIncomeConf::getCollectionName).collect(Collectors.toList());
                adminEcologyIncomeConfDetailsVO.setCollectionIds(collectionId);
                adminEcologyIncomeConfDetailsVO.setCollectionNames(collectionNames);
            }
            if (ecologyHatchCollecionShareProfitConf.getType() == EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT) {
                adminEcologyIncomeConfDetailsVO.setShareProfitSeparateAccountType(ecologyHatchCollecionShareProfitConf.getSeparateAccountType());
            }
            list.add(adminEcologyIncomeConfDetailsVO);
        }
        // 获取共振服务中心系数
        List<ResonanceServiceCenterCoefficientConf> resonanceServiceCenterCoefficientConfList = resonanceServiceCenterCoefficientConfDao.getListByEcologyHatchId(ecologyHatchConf.getId());
        List<ResonanceServiceCenterCoefficientConfVO> resonanceServiceCenterCoefficientConfVOList = BeanUtil.copyToList(resonanceServiceCenterCoefficientConfList, ResonanceServiceCenterCoefficientConfVO.class);
        vo.setList(list);
        vo.setResonanceServiceCenterCoefficientConfDTOList(resonanceServiceCenterCoefficientConfVOList);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateConf(AdminEcologyIncomeConfUpdateVO adminEcologyIncomeConfUpdateVO) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(adminEcologyIncomeConfUpdateVO.getConfId());
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));
        BigDecimal totalDistributionScale = BigDecimal.ZERO;
        // 获取分润方式
        EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(adminEcologyIncomeConfUpdateVO.getConfId());
        Assert.notNull(ecologyHatchShareProfitMethodConf, () -> new GlobalRunTimeException("生态分润方式不存在"));
        Assert.isTrue(adminEcologyIncomeConfUpdateVO.getType() == ecologyHatchShareProfitMethodConf.getType(), () -> new GlobalRunTimeException("不支持修改分润配置方式"));
        if (EcologyHatchShareProfitMethodConfTypeEnum.SMELTER_SMELTER == ecologyHatchShareProfitMethodConf.getType() && adminEcologyIncomeConfUpdateVO.getResonanceStatus()) {
            Assert.isTrue(!CollectionUtils.isEmpty(adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterCoefficientConfDTOList()) && adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterCoefficientConfDTOList().size() > 0, () -> new GlobalRunTimeException("共振服务中心系数考核配置不得为空"));
        }

        // 分润系数考核标准
        resonanceServiceCenterCoefficientConfDao.removeByConfId(adminEcologyIncomeConfUpdateVO.getConfId());
        List<ResonanceServiceCenterCoefficientConfDTO> resonanceServiceCenterCoefficientConfDTOs = new ArrayList<>();
        if (adminEcologyIncomeConfUpdateVO.getResonanceStatus()) {
            Long resonanceServiceCenterDaoId = ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId();
            if (Objects.isNull(resonanceServiceCenterDaoId)) {
                resonanceServiceCenterDaoId = adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId();
                CoefficientVO coefficientVO = getCoefficient(resonanceServiceCenterDaoId, ecologyHatchConf.getId(), ecologyHatchConf, adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterCoefficientConfDTOList());
                resonanceServiceCenterCoefficientConfDTOs = coefficientVO.getResonanceServiceCenterCoefficientConfDTOList();
                ecologyHatchShareProfitMethodConfDao.updateResonanceServiceCenterCoefficient(ecologyHatchShareProfitMethodConf.getId(), coefficientVO.getCoefficient());
            }
        } else {
            resonanceServiceCenterCoefficientConfDTOs = buildResonanceServiceCenterCoefficientConfDTOList(adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterCoefficientConfDTOList());
        }
        for (int i = 0; i < resonanceServiceCenterCoefficientConfDTOs.size(); i++) {
            ResonanceServiceCenterCoefficientConfDTO resonanceServiceCenterCoefficientConfDTO = resonanceServiceCenterCoefficientConfDTOs.get(i);
            if (BigDecimalUtils.compare(resonanceServiceCenterCoefficientConfDTO.getCoefficient(), 100)) {
                throw new GlobalRunTimeException("生态系数不得大于百分之100");
            }
            ResonanceServiceCenterCoefficientConf resonanceServiceCenterCoefficientConf = new ResonanceServiceCenterCoefficientConf();
            BeanUtil.copyProperties(resonanceServiceCenterCoefficientConfDTO, resonanceServiceCenterCoefficientConf);
            resonanceServiceCenterCoefficientConf.setLevel(i + 1);
            resonanceServiceCenterCoefficientConf.setEcologyHatchId(adminEcologyIncomeConfUpdateVO.getConfId());
            resonanceServiceCenterCoefficientConf.insert();
        }

        List<AdminEcologyIncomeConfDetailsVO> adminEcologyIncomeConfDetailsVOList = adminEcologyIncomeConfUpdateVO.getAdminEcologyIncomeConfDetailsVOList();
        for (AdminEcologyIncomeConfDetailsVO adminEcologyIncomeConfDetailsVO : adminEcologyIncomeConfDetailsVOList) {

            log.info(adminEcologyIncomeConfDetailsVO.getTypeName());

            totalDistributionScale = totalDistributionScale.add(adminEcologyIncomeConfDetailsVO.getDistributionScale());
            Assert.isTrue(NumberUtil.isGreaterOrEqual(adminEcologyIncomeConfDetailsVO.getDistributionScale(), BigDecimal.ZERO), () -> new GlobalRunTimeException("分配比例必须大于0"));

            //修改比例
            Long resonanceDaoId = checkAndUpdateDistribution(adminEcologyIncomeConfDetailsVO, adminEcologyIncomeConfUpdateVO.getResonanceStatus(), adminEcologyIncomeConfUpdateVO.getType(), ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId(), adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId());

            if (EcologyHatchShareProfitMethodConfTypeEnum.SMELTER_SMELTER == ecologyHatchShareProfitMethodConf.getType()) {
                // 谁熔炼归谁
                if (!ecologyHatchShareProfitMethodConf.getResonanceStatus().equals(adminEcologyIncomeConfUpdateVO.getResonanceStatus())) {
                    if (Objects.nonNull(adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId())) {
                        List<EcologyHatchConf> ecologyHatchConfs = ecologyHatchConfDao.list();
                        List<Long> daoIds = ecologyHatchConfs.stream().map(EcologyHatchConf::getDaoId).collect(Collectors.toList());
                        Assert.isFalse(daoIds.contains(adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId()), () -> new GlobalRunTimeException("品牌方不能作为共振方"));
                        EcologyHatchShareProfitMethodConf oneByResonanceServiceCenterDaoId = ecologyHatchShareProfitMethodConfDao.getOneByResonanceServiceCenterDaoId(adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId(), ecologyHatchShareProfitMethodConf.getId());
                        Assert.isNull(oneByResonanceServiceCenterDaoId, () -> new GlobalRunTimeException("该dao已经是共振方"));
                    }
                    ecologyHatchShareProfitMethodConfDao.updateStatusByEcologyHatchId(adminEcologyIncomeConfUpdateVO.getConfId(), adminEcologyIncomeConfUpdateVO.getResonanceStatus(),
                            adminEcologyIncomeConfUpdateVO.getResonanceServiceCenterDaoId(), ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId());
                }
                if (Objects.nonNull(resonanceDaoId)) {
                    ecologyHatchShareProfitMethodConfDao.updateResonanceDaoIdByEcologyHatchId(adminEcologyIncomeConfUpdateVO.getConfId(), resonanceDaoId);
                }
            }

            if (adminEcologyIncomeConfDetailsVO.getType() == EcologyHatchShareProfitTypeEnum.SHARE_PROFIT) {

                //如果数据库中的藏品id和前端传递的藏品id一致 则跳过
                List<EcologyHatchShareIncomeConf> listByConfId = ecologyHatchShareIncomeConfDao.getListByConfId(ecologyHatchConf.getId());
                List<Long> collect = listByConfId.stream().map(EcologyHatchShareIncomeConf::getCollectionId).collect(Collectors.toList());
                //判断传入的list和系统中 配置的直推藏品id是否一致
                if (collect.containsAll(adminEcologyIncomeConfDetailsVO.getCollectionIds()) && adminEcologyIncomeConfDetailsVO.getCollectionIds().containsAll(collect)) {
                    continue;
                } else {
                    //如果配置的有直推 则全部删除 重新插入
                    if (listByConfId.size() > 0) {
                        Assert.isTrue(ecologyHatchShareIncomeConfDao.removeByConfId(ecologyHatchConf.getId()), () -> new GlobalRunTimeException("删除生态收益配置失败"));
                    }
                    List<DigitalCollection> collections = digitalCollectionDao.getByIds(adminEcologyIncomeConfDetailsVO.getCollectionIds());
                    Assert.isTrue(collections.size() == adminEcologyIncomeConfDetailsVO.getCollectionIds().size(), () -> new GlobalRunTimeException("藏品id错误"));

                    for (DigitalCollection collection : collections) {
                        EcologyHatchShareIncomeConf ecologyHatchShareIncomeConf = new EcologyHatchShareIncomeConf();
                        ecologyHatchShareIncomeConf.setConfId(ecologyHatchConf.getId());
                        ecologyHatchShareIncomeConf.setCollectionId(collection.getId());
                        ecologyHatchShareIncomeConf.setCollectionName(collection.getFirstTitle());
                        ecologyHatchShareIncomeConf.setIncomeScale(adminEcologyIncomeConfDetailsVO.getDistributionScale());
                        ecologyHatchShareIncomeConf.insert();
                    }
                }
            } else if (adminEcologyIncomeConfDetailsVO.getType() == EcologyHatchShareProfitTypeEnum.BOTH_PARTIES_ACCOUNT || (ecologyHatchShareProfitMethodConf.getType() == EcologyHatchShareProfitMethodConfTypeEnum.FIXED_PROPORTION && adminEcologyIncomeConfDetailsVO.getType() == EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT)) {
                BigDecimal add = adminEcologyIncomeConfDetailsVO.getDaoDivideIntoScale().add(adminEcologyIncomeConfDetailsVO.getPlatformDivideScale());
                Assert.isTrue(NumberUtil.equals(add, Convert.toBigDecimal(100)), () -> new GlobalRunTimeException("平台分成比例和DAO分成比例之和必须为100%"));
            }
        }
        Assert.isTrue(NumberUtil.equals(totalDistributionScale.movePointLeft(2), BigDecimal.ONE), () -> new GlobalRunTimeException("分配比例总和必须为100%"));
    }

    @Override
    public Page<AdminEcologyIncomeConfListVO> getConfList(String collectionName, String daoName, Integer pageNo, Integer pageSize) {

        Page<AdminEcologyIncomeConfListVO> page = ecologyHatchConfDao.getPageByCollectionNameAndDaoName(collectionName, daoName, pageNo, pageSize);
        for (AdminEcologyIncomeConfListVO record : page.getRecords()) {
            record.setVOList(ecologyHatchShareIncomeConfDao.getConfList(record.getConfId()));
        }

        return page;
    }

    @Override
    public Page<AdminEcologyHatchDivideIntoLogVO> divideIntoPage(Long collectionId, Integer pageNo, Integer pageSize) {
        return ecologyHatchDivideIntoLogDao.divideIntoPage(collectionId, pageNo, pageSize);
    }

    @Override
    public void updateSeparateAccountType(Long confId, EcologyHatchShareProfitSeparateAccountTypeEnum separateAccountType) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(confId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));
        Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateSeparateAccountTypeByConfId(confId, separateAccountType), () -> new GlobalRunTimeException("更新双方分账类型失败"));
    }


    private Long checkAndUpdateDistribution(AdminEcologyIncomeConfDetailsVO vo, Boolean resonanceStatus, EcologyHatchShareProfitMethodConfTypeEnum methodType, Long resonanceServiceCenterDaoId, Long updateResonanceServiceCenterDaoId) {
        Long resonanceDaoId = null;
        EcologyHatchCollecionShareProfitConf oneByConfIdAndType = ecologyHatchCollecionShareProfitConfDao.getOneByConfIdAndType(vo.getConfId(), vo.getType());
        Assert.notNull(oneByConfIdAndType, () -> new GlobalRunTimeException("生态熔炼收益配置不存在"));
        if (!NumberUtil.equals(oneByConfIdAndType.getDistributionScale(), vo.getDistributionScale())) {
            Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateDistributionScaleById(oneByConfIdAndType.getId(), vo.getDistributionScale()), () -> new GlobalRunTimeException("更新生态收益配置失败"));
        }
        if (EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT == vo.getType() && EcologyHatchShareProfitMethodConfTypeEnum.SMELTER_SMELTER == methodType && resonanceStatus) {
            Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateScaleById(oneByConfIdAndType.getId(), vo.getServiceCenterNewUserNum(), vo.getDaoNewUserNum(), vo.getResonanceDaoDivideIntoScale(), vo.getResonanceServiceCenterDaoDivideIntoScale()), () -> new GlobalRunTimeException("更新生态收益配置失败"));
        }

        if (oneByConfIdAndType.getType() != EcologyHatchShareProfitTypeEnum.PLATFORM_DIVIDE && oneByConfIdAndType.getDaoId() != vo.getDaoId()) {
            if (EcologyHatchShareProfitTypeEnum.MARKET_VALUE_MANAGEMENT == oneByConfIdAndType.getType()) {
                if (Objects.isNull(resonanceServiceCenterDaoId)) {
                    resonanceDaoId = vo.getDaoId();
                    Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateDaoId(oneByConfIdAndType.getId(), vo.getDaoId()), () -> new GlobalRunTimeException("更新生态收益配置失败"));
                    if (Objects.nonNull(updateResonanceServiceCenterDaoId)) {
                        Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateServiceCenterDaoId(oneByConfIdAndType.getId(), updateResonanceServiceCenterDaoId), () -> new GlobalRunTimeException("更新生态收益配置失败"));
                    }
                }
            } else if (EcologyHatchShareProfitTypeEnum.PER_DIVIDEND_POOL == oneByConfIdAndType.getType()) {
                if (Objects.isNull(resonanceServiceCenterDaoId) && Objects.nonNull(updateResonanceServiceCenterDaoId)) {
                    Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateServiceCenterDaoId(oneByConfIdAndType.getId(), updateResonanceServiceCenterDaoId), () -> new GlobalRunTimeException("更新生态收益配置失败"));
                }
            } else {
                Assert.isTrue(ecologyHatchCollecionShareProfitConfDao.updateDaoId(oneByConfIdAndType.getId(), vo.getDaoId()), () -> new GlobalRunTimeException("更新生态收益配置失败"));
            }
        }
        return resonanceDaoId;
    }


    /**
     * 共振分润系数同步
     */
    @Override
    public void resonanceSeparationCoefficientsAreSynchronized() {
        // 获取所有的分润系数
        List<ResonanceServiceCenterCoefficientConf> resonanceServiceCenterCoefficientConfList = resonanceServiceCenterCoefficientConfDao.list();
        // 获取熔炼配置id 对应的 系数
        Map<Long, List<ResonanceServiceCenterCoefficientConf>> resonanceServiceCenterCoefficientConfMap = resonanceServiceCenterCoefficientConfList.stream().collect(Collectors.groupingBy(ResonanceServiceCenterCoefficientConf::getEcologyHatchId));
        for (Long ecologyHatchId : resonanceServiceCenterCoefficientConfMap.keySet()) {
            // 获取分润配置方式
            EcologyHatchShareProfitMethodConf ecologyHatchShareProfitMethodConf = ecologyHatchShareProfitMethodConfDao.getOneByEcologyHatchId(ecologyHatchId);
            if (Objects.isNull(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId())) {
                ecologyHatchShareProfitMethodConfDao.updateResonanceServiceCenterCoefficientById(ecologyHatchShareProfitMethodConf.getId(), BigDecimal.ZERO);
            }
            EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(ecologyHatchId);
            // 品牌
            UserCreatorInfo daoUser = userCreatorInfoDao.getById(ecologyHatchShareProfitMethodConf.getResonanceDaoId());
            UserCreatorInfo resonanceServiceCenter = userCreatorInfoDao.getById(ecologyHatchShareProfitMethodConf.getResonanceServiceCenterDaoId());
            Integer userNum = userInfoDao.getCountValidByUserId(resonanceServiceCenter.getUserId(), daoUser.getUserId());
            List<ResonanceServiceCenterCoefficientConf> resonanceServiceCenterCoefficientConfs = resonanceServiceCenterCoefficientConfMap.get(ecologyHatchId);
            for (ResonanceServiceCenterCoefficientConf resonanceServiceCenterCoefficientConf : resonanceServiceCenterCoefficientConfs) {
                if (resonanceServiceCenterCoefficientConf.getMinNum() < userNum && resonanceServiceCenterCoefficientConf.getMaxNum() >= userNum) {
                    ecologyHatchShareProfitMethodConfDao.updateResonanceServiceCenterCoefficientById(ecologyHatchShareProfitMethodConf.getId(), resonanceServiceCenterCoefficientConf.getCoefficient());
                    break;
                }
            }
        }
    }


    /**
     * 新增生态收益配置
     *
     * @param confId
     * @param singleList
     * @param serviceCenterList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addConfNew(Long confId, List<AddEcologyIncomeConfSingleRequest> singleList, List<ADDEcologyIncomeServiceCenterConfRequest> serviceCenterList) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(confId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));
        BigDecimal distributionScaleSum = singleList.stream().map(AddEcologyIncomeConfSingleRequest::getDistributionScale).reduce(BigDecimal.ZERO, BigDecimal::add);
        Assert.isTrue(distributionScaleSum.compareTo(new BigDecimal(100)) <= 0, () -> new GlobalRunTimeException("分润占比不能大于100%"));
        // 新增单方收益配置
        List<EcologyCollectionShareProfitConf> shareProfitConfList = new ArrayList<>();
        for (AddEcologyIncomeConfSingleRequest addEcologyIncomeConfSingleRequest : singleList) {
            EcologyCollectionShareProfitConf ecologyCollectionShareProfitConf = new EcologyCollectionShareProfitConf();
            ecologyCollectionShareProfitConf.setConfId(confId);
            ecologyCollectionShareProfitConf.setType(addEcologyIncomeConfSingleRequest.getType());
            ecologyCollectionShareProfitConf.setTypeName(addEcologyIncomeConfSingleRequest.getType().getDescription());
            ecologyCollectionShareProfitConf.setDistributionScale(addEcologyIncomeConfSingleRequest.getDistributionScale());
            ecologyCollectionShareProfitConf.setCollectionId(ecologyHatchConf.getCollectionId());
            shareProfitConfList.add(ecologyCollectionShareProfitConf);
            switch (addEcologyIncomeConfSingleRequest.getType()) {
                case SHARE_PROFIT:
                    if (CollectionUtils.isEmpty(addEcologyIncomeConfSingleRequest.getCollectionList())) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【藏品不能为空】");
                    }
                    for (AddEcologyIncomeCollectionRequest addEcologyIncomeCollectionRequest : addEcologyIncomeConfSingleRequest.getCollectionList()) {
                        EcologyHatchShareIncomeConf ecologyHatchShareIncomeConf = new EcologyHatchShareIncomeConf();
                        ecologyHatchShareIncomeConf.setConfId(confId);
                        ecologyHatchShareIncomeConf.setCollectionId(addEcologyIncomeCollectionRequest.getId());
                        ecologyHatchShareIncomeConf.setCollectionName(addEcologyIncomeCollectionRequest.getCollectionName());
                        ecologyHatchShareIncomeConf.setIncomeScale(addEcologyIncomeConfSingleRequest.getDistributionScale());
                        ecologyHatchShareIncomeConfDao.save(ecologyHatchShareIncomeConf);
                    }
                    break;
                case RISK_POOL:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case PLATFORM_DIVIDE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case DAO_DIVIDE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case PER_DIVIDEND_POOL:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case TECHNICAL_SERVICE_FEE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
            }
        }
        Assert.isTrue(ecologyCollectionShareProfitConfService.saveAll(shareProfitConfList), () -> new GlobalRunTimeException("分润配置保存失败"));
        if (!CollectionUtils.isEmpty(serviceCenterList)) {
            List<Long> collect = serviceCenterList.stream().map(ADDEcologyIncomeServiceCenterConfRequest::getDaoId).distinct().collect(Collectors.toList());
            if (collect.size() != serviceCenterList.size()) {
                throw new GlobalRunTimeException("服务中心重复");
            }
            List<EcologyShareProfitServiceCenterConf> serviceCenterConfList = new ArrayList<>();
            for (ADDEcologyIncomeServiceCenterConfRequest request : serviceCenterList) {
                EcologyShareProfitServiceCenterConf ecologyShareProfitServiceCenterConf = new EcologyShareProfitServiceCenterConf();
                ecologyShareProfitServiceCenterConf.setConfId(confId);
                ecologyShareProfitServiceCenterConf.setCollectionId(ecologyHatchConf.getCollectionId());
                ecologyShareProfitServiceCenterConf.setDaoId(request.getDaoId());
                ecologyShareProfitServiceCenterConf.setNewUserNum(request.getNewUserNum());
                ecologyShareProfitServiceCenterConf.setSmeltingNum(request.getSmeltingNum());
                ecologyShareProfitServiceCenterConf.setResonanceDaoDivideIntoScale(request.getResonanceDaoDivideIntoScale());
                ecologyShareProfitServiceCenterConf.setResonanceServiceCenterDaoDivideIntoScale(request.getResonanceServiceCenterDaoDivideIntoScale());
                serviceCenterConfList.add(ecologyShareProfitServiceCenterConf);
            }
            Assert.isTrue(ecologyShareProfitServiceCenterConfService.saveAll(serviceCenterConfList), () -> new GlobalRunTimeException("服务中心配置保存失败"));

        }

    }


    /**
     * 配置详情
     *
     * @param confId
     * @return
     */
    @Override
    public ADDEcologyIncomeConfNewDetailsVO getNewByConfId(Long confId) {
        ADDEcologyIncomeConfNewDetailsVO addEcologyIncomeConfNewDetailsVO = new ADDEcologyIncomeConfNewDetailsVO();
        addEcologyIncomeConfNewDetailsVO.setConfId(confId);

        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(confId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));
        List<EcologyCollectionShareProfitConf> shareProfitConfList = ecologyCollectionShareProfitConfService.listByConfId(confId);
        addEcologyIncomeConfNewDetailsVO.setSingleList(BeanUtil.copyToList(shareProfitConfList, AddEcologyIncomeConfSingleVO.class));
        for (AddEcologyIncomeConfSingleVO addEcologyIncomeConfSingleVO : addEcologyIncomeConfNewDetailsVO.getSingleList()) {
            if (addEcologyIncomeConfSingleVO.getType() == EcologyCollectionShareProfitTypeEnum.SHARE_PROFIT) {
                List<EcologyHatchShareIncomeConf> incomeConfList = ecologyHatchShareIncomeConfDao.getListByConfId(confId);
                List<AddEcologyIncomeCollectionRequest> collectionList = new ArrayList<>();
                for (EcologyHatchShareIncomeConf ecologyHatchShareIncomeConf : incomeConfList) {
                    AddEcologyIncomeCollectionRequest addEcologyIncomeCollectionRequest = new AddEcologyIncomeCollectionRequest();
                    addEcologyIncomeCollectionRequest.setId(ecologyHatchShareIncomeConf.getCollectionId());
                    addEcologyIncomeCollectionRequest.setCollectionName(ecologyHatchShareIncomeConf.getCollectionName());
                    collectionList.add(addEcologyIncomeCollectionRequest);
                }
                addEcologyIncomeConfSingleVO.setCollectionList(collectionList);
            }
        }
        List<EcologyShareProfitServiceCenterConf> centerConfList = ecologyShareProfitServiceCenterConfService.listByConfId(confId);
        if (!CollectionUtils.isEmpty(centerConfList)) {
            addEcologyIncomeConfNewDetailsVO.setServiceCenterList(BeanUtil.copyToList(centerConfList, ADDEcologyIncomeServiceCenterConfVO.class));
        }
        return addEcologyIncomeConfNewDetailsVO;
    }


    /**
     * 编辑配置
     *
     * @param confId
     * @param singleList
     * @param serviceCenterList
     */
    @Override
    @Transactional
    public void updateConfNew(Long confId, List<AddEcologyIncomeConfSingleRequest> singleList, List<ADDEcologyIncomeServiceCenterConfRequest> serviceCenterList) {
        EcologyHatchConf ecologyHatchConf = ecologyHatchConfDao.getById(confId);
        Assert.notNull(ecologyHatchConf, () -> new GlobalRunTimeException("生态铸造配置不存在"));
        BigDecimal distributionScaleSum = singleList.stream().map(AddEcologyIncomeConfSingleRequest::getDistributionScale).reduce(BigDecimal.ZERO, BigDecimal::add);
        Assert.isTrue(distributionScaleSum.compareTo(new BigDecimal(100)) <= 0, () -> new GlobalRunTimeException("分润占比不能大于100%"));
        //删除直推配置
        ecologyHatchShareIncomeConfDao.removeByConfId(confId);
        Long perDividendPoolDaoId = 0L;
        // 新增单方收益配置
        for (AddEcologyIncomeConfSingleRequest addEcologyIncomeConfSingleRequest : singleList) {
            EcologyCollectionShareProfitConf ecologyCollectionShareProfitConf = new EcologyCollectionShareProfitConf();
            ecologyCollectionShareProfitConf.setId(addEcologyIncomeConfSingleRequest.getId());
            ecologyCollectionShareProfitConf.setConfId(confId);
            ecologyCollectionShareProfitConf.setType(addEcologyIncomeConfSingleRequest.getType());
            ecologyCollectionShareProfitConf.setTypeName(addEcologyIncomeConfSingleRequest.getType().getDescription());
            ecologyCollectionShareProfitConf.setDistributionScale(addEcologyIncomeConfSingleRequest.getDistributionScale());
            ecologyCollectionShareProfitConf.setCollectionId(ecologyHatchConf.getCollectionId());
            switch (addEcologyIncomeConfSingleRequest.getType()) {
                case SHARE_PROFIT:
                    if (CollectionUtils.isEmpty(addEcologyIncomeConfSingleRequest.getCollectionList())) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【藏品不能为空】");
                    }
                    for (AddEcologyIncomeCollectionRequest addEcologyIncomeCollectionRequest : addEcologyIncomeConfSingleRequest.getCollectionList()) {
                        EcologyHatchShareIncomeConf ecologyHatchShareIncomeConf = new EcologyHatchShareIncomeConf();
                        ecologyHatchShareIncomeConf.setConfId(confId);
                        ecologyHatchShareIncomeConf.setCollectionId(addEcologyIncomeCollectionRequest.getId());
                        ecologyHatchShareIncomeConf.setCollectionName(addEcologyIncomeCollectionRequest.getCollectionName());
                        ecologyHatchShareIncomeConf.setIncomeScale(addEcologyIncomeConfSingleRequest.getDistributionScale());
                        ecologyHatchShareIncomeConfDao.save(ecologyHatchShareIncomeConf);
                    }
                    break;
                case RISK_POOL:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case PLATFORM_DIVIDE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case DAO_DIVIDE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case PER_DIVIDEND_POOL:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    perDividendPoolDaoId = addEcologyIncomeConfSingleRequest.getDaoId();
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
                case TECHNICAL_SERVICE_FEE:
                    if (addEcologyIncomeConfSingleRequest.getDaoId() == null || addEcologyIncomeConfSingleRequest.getDaoId() == 0) {
                        throw new GlobalRunTimeException(addEcologyIncomeConfSingleRequest.getType().getDescription() + "【DAO不能为空】");
                    }
                    ecologyCollectionShareProfitConf.setDaoId(addEcologyIncomeConfSingleRequest.getDaoId());
                    break;
            }
            Assert.isTrue(ecologyCollectionShareProfitConfService.updateById(ecologyCollectionShareProfitConf), () -> new GlobalRunTimeException("更新配置失败"));
        }
        if (!CollectionUtils.isEmpty(serviceCenterList)) {
            List<Long> collect = serviceCenterList.stream().map(ADDEcologyIncomeServiceCenterConfRequest::getDaoId).distinct().collect(Collectors.toList());
            if (collect.size() != serviceCenterList.size()) {
                throw new GlobalRunTimeException("服务中心重复");
            }
            if (collect.contains(perDividendPoolDaoId)) {
                throw new GlobalRunTimeException("服务中心和品牌方重复");
            }

            for (ADDEcologyIncomeServiceCenterConfRequest request : serviceCenterList) {
                BigDecimal sum = request.getResonanceServiceCenterDaoDivideIntoScale().add(request.getResonanceDaoDivideIntoScale());
                Assert.isTrue(sum.compareTo(new BigDecimal(100)) <= 0, () -> new GlobalRunTimeException("共振分成比例不能大于100%"));
                EcologyShareProfitServiceCenterConf ecologyShareProfitServiceCenterConf = new EcologyShareProfitServiceCenterConf();
                ecologyShareProfitServiceCenterConf.setId(request.getId());
                ecologyShareProfitServiceCenterConf.setConfId(confId);
                ecologyShareProfitServiceCenterConf.setCollectionId(ecologyHatchConf.getCollectionId());
                ecologyShareProfitServiceCenterConf.setDaoId(request.getDaoId());
                ecologyShareProfitServiceCenterConf.setNewUserNum(request.getNewUserNum());
                ecologyShareProfitServiceCenterConf.setSmeltingNum(request.getSmeltingNum());
                ecologyShareProfitServiceCenterConf.setResonanceDaoDivideIntoScale(request.getResonanceDaoDivideIntoScale());
                ecologyShareProfitServiceCenterConf.setResonanceServiceCenterDaoDivideIntoScale(request.getResonanceServiceCenterDaoDivideIntoScale());
                Assert.isTrue(ecologyShareProfitServiceCenterConfService.saveOrUpdate(ecologyShareProfitServiceCenterConf), () -> new GlobalRunTimeException("服务中心配置保存失败"));
            }
        }else {
            ecologyShareProfitServiceCenterConfService.removeByConfId(confId);
        }
    }


    /**
     * 获取收益配置列表(新)
     *
     * @param collectionName
     * @param daoName
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<AdminEcologyIncomeConfListVO> getNewConfList(String collectionName, String daoName, Integer pageNo, Integer pageSize) {
        Page<AdminEcologyIncomeConfListVO> page = ecologyHatchConfDao.getPageByCollectionNameAndDaoName(collectionName, daoName, pageNo, pageSize);
        if (Objects.nonNull(page) && !CollectionUtils.isEmpty(page.getRecords())) {
            for (AdminEcologyIncomeConfListVO record : page.getRecords()) {
                record.setNewVOList(ecologyCollectionShareProfitConfService.getConfList(record.getConfId()));
            }

        }
        return page;
    }
}
